<script setup>
import { ref, onMounted, watch } from 'vue'
import { Menu, Timer, Monitor, CaretTop } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 模拟数据
const timeRange = ref('week')

const appStats = ref({
  total: 128,
  trend: 15
})

const taskStats = ref({
  total: 256,
  running: 180
})

const robotStats = ref({
  total: 50,
  online: 42
})

const robotStatusList = ref([
  {
    label: '在线',
    count: 42,
    percentage: 84,
    type: 'success'
  },
  {
    label: '离线',
    count: 5,
    percentage: 10,
    type: 'danger'
  },
  {
    label: '维护中',
    count: 3,
    percentage: 6,
    type: 'warning'
  }
])

// 生成模拟数据
const generateMockData = (range) => {
  const now = new Date()
  const data = []
  let days = 0
  let format = ''
  
  switch(range) {
    case 'week':
      days = 7
      format = 'MM-DD'
      break
    case 'month':
      days = 30
      format = 'MM-DD'
      break
    case 'year':
      days = 12
      format = 'YYYY-MM'
      break
  }

  if (range === 'year') {
    // 按月生成数据
    for (let i = 11; i >= 0; i--) {
      const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
      const month = date.toISOString().slice(0, 7)
      data.push([
        month,
        Math.floor(Math.random() * 100 + 150), // 完成任务
        Math.floor(Math.random() * 50 + 20),   // 失败任务
        Math.floor(Math.random() * 30 + 10)    // 等待中任务
      ])
    }
  } else {
    // 按天生成数据
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
      const day = date.toISOString().slice(0, 10)
      data.push([
        day,
        Math.floor(Math.random() * 30 + 50),  // 完成任务
        Math.floor(Math.random() * 10 + 5),   // 失败任务
        Math.floor(Math.random() * 8 + 3)     // 等待中任务
      ])
    }
  }
  
  return data
}

// 图表实例
let chartInstance = null

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('taskTrendChart')
  if (!chartDom) return
  
  chartInstance = echarts.init(chartDom)
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const data = generateMockData(timeRange.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['完成任务', '失败任务', '等待中任务'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item[0]),
      axisLabel: {
        rotate: timeRange.value === 'month' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '完成任务',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: data.map(item => item[1]),
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '失败任务',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: data.map(item => item[2]),
        itemStyle: {
          color: '#F56C6C'
        }
      },
      {
        name: '等待中任务',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: data.map(item => item[3]),
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

// 监听时间范围变化
watch(() => timeRange.value, () => {
  updateChart()
})

// 监听窗口大小变化
const handleResize = () => {
  chartInstance && chartInstance.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
const onUnmounted = () => {
  window.removeEventListener('resize', handleResize)
  chartInstance && chartInstance.dispose()
}
</script>

<template>
  <div class="dashboard-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="40" class="blue"><Menu /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ appStats.total }}</div>
              <div class="stat-label">RPA应用总数</div>
              <div class="stat-trend" :class="{ 'up': appStats.trend > 0 }">
                <el-icon><CaretTop /></el-icon>
                较上月{{ Math.abs(appStats.trend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="40" class="green"><Timer /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ taskStats.running }}/{{ taskStats.total }}</div>
              <div class="stat-label">任务执行情况</div>
              <el-progress 
                :percentage="(taskStats.running / taskStats.total) * 100" 
                :stroke-width="8"
                :format="(format) => `执行率 ${format}%`"
              />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="40" class="purple"><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ robotStats.online }}/{{ robotStats.total }}</div>
              <div class="stat-label">机器人状态</div>
              <el-progress 
                :percentage="(robotStats.online / robotStats.total) * 100" 
                :stroke-width="8"
                status="success"
                :format="(format) => `在线率 ${format}%`"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>任务执行趋势</span>
              <el-radio-group v-model="timeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div id="taskTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>机器人状态分布</span>
            </div>
          </template>
          <div class="status-list">
            <div v-for="(status, index) in robotStatusList" :key="index" class="status-item">
              <div class="status-label">
                <el-tag :type="status.type" size="small">{{ status.label }}</el-tag>
                <span class="status-count">{{ status.count }}</span>
              </div>
              <el-progress 
                :percentage="status.percentage" 
                :status="status.type === 'success' ? 'success' : status.type === 'warning' ? 'warning' : 'exception'"
                :stroke-width="8"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stat-card {
  height: 160px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  height: 100%;
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border-radius: 40px;
  background: var(--el-color-primary-light-9);
}

.stat-icon .blue {
  color: var(--el-color-primary);
}

.stat-icon .green {
  color: var(--el-color-success);
}

.stat-icon .purple {
  color: var(--el-color-purple);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  line-height: 1.2;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-bottom: 12px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: var(--el-color-danger);
}

.stat-trend.up {
  color: var(--el-color-success);
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.status-list {
  padding: 20px;
}

.status-item {
  margin-bottom: 24px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.status-count {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

:deep(.el-progress-bar__inner) {
  transition: all 0.3s ease;
}

:deep(.el-card__body) {
  height: calc(100% - 60px);
  padding: 20px;
}
</style> 